package special;

import java.security.Key;
import java.util.*;
import java.util.function.BiConsumer;

/**
 * leetcode_1032
 */
public class StreamChecker {
    private String[] words;
    private Map<Character, Map<Integer, List<Integer>>> map = new HashMap<>();
    private StringBuilder input = new  StringBuilder();
    public StreamChecker(String[] words) {
        System.out.println();
        this.words = words;
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            char key1 =   word.charAt(word.length() - 1);
            int key2 = word.length();
            if (map.containsKey(key1)){
                Map<Integer, List<Integer>> map2 = map.get(key1);
                if (map2.containsKey(key2)){
                    List<Integer> list = map2.get(word.length());
                    list.add(i);
                }else {
                    List<Integer> list = new ArrayList<>();
                    list.add(i);
                    map2.put(key2, list);
                }
            }else {
                HashMap<Integer, List<Integer>> map2 = new HashMap<>();
                List<Integer> list = new ArrayList<>();
                list.add(i);
                map2.put(key2, list);
                map.put(key1, map2);
            }
        }
    }

    public boolean query(char letter) {
        input.append(letter);
        int len = input.length();
        if (map.containsKey(letter)){
            Map<Integer, List<Integer>> map2 = map.get(letter);
            Set<Integer> key2s = map2.keySet();
            for (Integer key2 : key2s) {
                if (key2 > len)
                    continue;
                List<Integer> list = map2.get(key2);
                for (Integer i : list) {
                    if (input.substring(len - key2, len).equals(words[i]))
                        return true;
                }
            }
        }
        return false;
    }
}
